import React, { lazy, Suspense } from 'react';
import { Redirect, Route, Switch } from 'react-router-dom';

import Loading from '@/components/blank/loading';
import UserModel, { IMenu } from '@/models/user';

import BasicLayout from '../layouts/BasicLayout';
import routeMaps from './routes';

const Page403 = lazy(() => import('@/pages/user/_errors/page403'));
const Page404 = lazy(() => import('@/pages/user/_errors/page404'));
const Page500 = lazy(() => import('@/pages/user/_errors/page500'));

const RouterPage = () => {
  const { hasAuth, routes } = UserModel();

  return (
    <>
      {hasAuth && (
        <BasicLayout>
          <Suspense fallback={<Loading />}>
            <Route exact path="/" render={() => <Redirect to="/home" />} />
            <Switch>
              {routes.map((v: IMenu) => {
                return v.redirect ? (
                  <Route
                    exact
                    key={v.code}
                    path={v.path}
                    component={() => <Redirect to={{ pathname: v.redirect }} />}
                  />
                ) : (
                  <Route exact key={v.code} path={v.path} component={routeMaps[v.code]} />
                );
              })}

              <Route exact path="/403" component={Page403} />
              <Route exact path="/500" component={Page500} />
              <Route component={Page404} />
            </Switch>
          </Suspense>
        </BasicLayout>
      )}
    </>
  );
};

export default RouterPage;
